package suery;

import java.awt.Component;
import java.awt.Container;

import javax.swing.RootPaneContainer;

import java.util.List;

/**
 * The tree of component.
 * 
 * @author Jeky
 */
public class ComponentTree {

    public ComponentTree() {
        this.root = new ComponentTreeNode(null);
    }

    /**
     * Analyze the top level container (JFrame, JDialog, JWindow and so on). And
     * initialize the nodes presenting the components.
     * 
     * @param topLevelContainer top level container
     */
    public void analyze(RootPaneContainer topLevelContainer) {
        ComponentTreeNode node = null;
        Container container = (Container) topLevelContainer;
        // find out whether the container has been analyzed
        List<ComponentTreeNode> children = root.getChildren();
        for (ComponentTreeNode child : children) {
            if (child.getComponent().equals(container)) {
                node = child;
                break;
            }
        }
        // if this container has not been analyzed, create new node
        if (node == null) {
            node = new ComponentTreeNode(container);
            root.addChild(node);
        }
        Container contentPane = topLevelContainer.getContentPane();
        analyzeContainer(contentPane, node);
    }

    /**
     * Get the root of component tree.
     * 
     * @return the root of component tree
     */
    public ComponentTreeNode getRoot() {
        return root;
    }

    private void analyzeContainer(Container container, ComponentTreeNode parent) {
        Component[] components = container.getComponents();
        for (Component c : components) {
            ComponentTreeNode node = new ComponentTreeNode(c);
            parent.addChild(node);
            if (c instanceof Container) {
                analyzeContainer((Container) c, node);
            }
        }
    }

    private final ComponentTreeNode root;
}
